package my.soft.aiteacher.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;

public class SignatureGenerator {
    private static final String APP_ID = "68d2eee6";
    private static final String SECRET_KEY = "4165290399881e6103f622f68484fc09";

    public static String generateSigna() {
        // 1. 获取当前时间戳(秒级)
        long ts = System.currentTimeMillis() / 1000;

        // 2. 生成baseString = APP_ID + ts
        String baseString = APP_ID + ts;

        // 3. 对baseString进行MD5
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] md5Bytes = md.digest(baseString.getBytes(StandardCharsets.UTF_8));
            String md5Result = bytesToHex(md5Bytes);
            Mac sha1Hmac = Mac.getInstance("HmacSHA1");
            SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
            sha1Hmac.init(secretKey);
            byte[] hmacBytes = sha1Hmac.doFinal(md5Result.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(hmacBytes);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("生成失败");
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static void main(String[] args) throws Exception {
        String signa = generateSigna();
        System.out.println("生成的签名: " + signa);
    }
}